//
//  AddAddressInfoController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/7/28.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "AddAddressInfoController.h"
#import "AddAddressCell.h"
#import "MainViewController.h"//选择地址

@interface AddAddressInfoController ()<UITableViewDelegate, UITableViewDataSource>

{
    NSString *nameStr;
    NSString *phoneStr;
    NSString *addressStr;
    NSString *doorNumStr;
    
    
    NSString *prov;
    NSString *city;
    NSString *area;
    NSString *lon;
    NSString *lat;
    
}

@property (nonatomic, strong)UIButton *rightBtn;//左侧按钮

@property (nonatomic, strong) UIButton *searchButton;

@end

@implementation AddAddressInfoController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle =UIStatusBarStyleDefault ;

}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    doorNumStr = @"0000";
    // Do any additional setup after loading the view from its nib.
    [self configureNav];//配置导航栏
    [self configureView];//配置控制器
    //注册传值通知，获取职位发布地址
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(chooseAddress:) name:@"chooseAddress" object:nil];
  
}
//获取职位地址的通知方法
- (void)chooseAddress:(NSNotification *)notification {
    //获取userInfo
    NSDictionary *userInfo = notification.userInfo;
    //获取字符串 并且赋值
    addressStr = userInfo[@"address"];
    lat = userInfo[@"lwd"];
    lon = userInfo[@"ljd"];
    
    prov = userInfo[@"pro"];
    city = userInfo[@"city"];
    area = userInfo[@"area"];
    
    //一个cell刷新
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:1];
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
}


- (void)configureNav {
      //self.navigationController.navigationBar.translucent = NO;
 
    
    //设置导航栏按钮的边距
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [_rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [_rightBtn addTarget:self action:@selector(onClickLeft) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 25)];
    if (self.pushType.integerValue == 1) {
        label.text = @"修改地址";

    }else{
        label.text = @"添加地址";

    }
    label.textColor = [UIColor blackColor];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
 
}
- (void)onClickLeft {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark 配置控制器
- (void)configureView {
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.separatorStyle = kSpNone;
    [_tableView registerNib:[UINib nibWithNibName:@"AddAddressCell" bundle:nil] forCellReuseIdentifier:@"AddAddressCell"];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

        return 2;
   
    
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
    return 10;    
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView  *bg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_Width, 10)];
    bg.backgroundColor = KShouYeBg;
    return bg;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    AddAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AddAddressCell"];
    cell.selectionStyle = kSeNone;
    
    if (_pushType.integerValue == 1) {
        nameStr = self.modle.full_name;
        phoneStr = self.modle.tel;
        addressStr = self.modle.address;
        doorNumStr = self.modle.house_number;
        
        prov = self.modle.prov;
        city = self.modle.city;
        area = self.modle.area;
        lon = self.modle.longitude;
        lat = self.modle.latitude;

    }
    
    
    if (indexPath.section == 0) {
        NSString *tit;
        NSString *placTStr;
        cell.jiantouImage.hidden = YES;
        if (indexPath.row == 0) {
            tit = @"联系人";
        
            if (nameStr == nil || nameStr == NULL) {
                
                cell.conTF.placeholder = @"请填写联系人姓名";
            }else {
                cell.conTF.text = nameStr;
            }
        }
        if (indexPath.row == 1) {
            tit = @"联系电话";
            if (phoneStr == nil || phoneStr == NULL) {
                
                cell.conTF.placeholder = @"请填写联系电话";
            }else {
                cell.conTF.text = phoneStr;
            }
        }
        cell.tiltLB.text = tit;
        
        cell.conTF.tag = 200+indexPath.row;
        [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        
        
    }
    if (indexPath.section == 1) {
        NSString *tit;
        NSString *placTStr;
       
        if (indexPath.row == 0) {
            tit = @"详细地址";
            placTStr = @"请选择详细地址";
            cell.jiantouImage.hidden = NO;
            cell.conTF.userInteractionEnabled = NO;
        
            if (addressStr == nil || addressStr == NULL) {
            
                cell.conTF.placeholder = @"请选择详细地址";
            }else {
                cell.conTF.text = addressStr;
            }
            
            
        }
        if (indexPath.row == 1) {
            tit = @"门牌号";
            placTStr = @"请填写门牌号";
            cell.jiantouImage.hidden = YES;
            if (doorNumStr == nil || doorNumStr == NULL || [doorNumStr isEqualToString:@"0000"]) {
                
                cell.conTF.placeholder = @"请选择详细地址";
            }else {
                cell.conTF.text = doorNumStr;
            }
        }
        cell.tiltLB.text = tit;
        cell.conTF.tag = 300+indexPath.row;
        [cell.conTF addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return cell;
    
    
}
//实时监听获取添加地址每个textF的值
- (void)textFieldEditChanged:(UITextField *)text {
    NSLog(@"%ld",text.tag);
    switch (text.tag) {
        case 200:
            nameStr = text.text;
            break;
        case 201:
            phoneStr = text.text;
            break;
        case 300:
            addressStr = text.text;
            break;
        case 301:
            doorNumStr = text.text;
            break;
            
        default:
            break;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            MainViewController *map = [[MainViewController alloc] init];
            [self.navigationController pushViewController:map animated:nil];
        }
    }
   
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark 保存地址按钮的点击事件
- (IBAction)saveAddressBtnAction:(UIButton *)sender {
    
    if ([self isBlankString:nameStr] == YES) {
        [MBProgressHUD showText:@"请输入联系人姓名"];
        return;
    }
    
    if ([self isBlankString:phoneStr] == YES) {
         [MBProgressHUD showText:@"请输入联系电话"];
        return;
    }
    
    if ([self isBlankString:addressStr] == YES) {
        [MBProgressHUD showText:@"请输入详细地址"];
        return;
    }
    
    if ([self isBlankString:doorNumStr] == YES) {
          [MBProgressHUD showText:@"请输入门牌号"];
        return;
    }

  

    
    if (_pushType.integerValue == 1) {
        //取本地的userid
        NSDictionary *saveDic = [SaveDataMethord readLoginData];
        NSDictionary *Dic = @{@"userid":saveDic[@"userid"],@"id":self.modle.Id,@"full_name":nameStr,@"tel":phoneStr,@"prov":prov,@"city":city,@"area":area,@"address":addressStr,@"house_number":doorNumStr,@"longitude":lon,@"latitude":lat,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        [HttpRequest postWithURLString:POST(Shop_EditAddress) parameters:Dic success:^(id responseObject) {
            NSLog(@"---- %@", responseObject);
            if ([responseObject[@"ret"] intValue] != 200 ) {
                [MBProgressHUD showText:@"编辑地址错误，请重新尝试"];
                return ;
            }
            [self.navigationController popViewControllerAnimated:YES];
        } failure:^(NSError *error) {
            
        }];
        
    }
    else{
        //取本地的userid
        NSDictionary *saveDic = [SaveDataMethord readLoginData];
        NSDictionary *Dic = @{@"userid":saveDic[@"userid"],@"full_name":nameStr,@"tel":phoneStr,@"prov":prov,@"city":city,@"area":area,@"address":addressStr,@"house_number":doorNumStr,@"longitude":lon,@"latitude":lat,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        
        [HttpRequest postWithURLString:POST(AddShopAddress) parameters:Dic success:^(id responseObject) {
            NSLog(@"---- %@", responseObject);
            if ([responseObject[@"ret"] intValue] != 200 ) {
                [MBProgressHUD showText:@"添加地址错误，请重新尝试"];
                return ;
            }
            [self.navigationController popViewControllerAnimated:YES];
            
        } failure:^(NSError *error) {
            
        }];
    }

}

//判断一个字符串是否为空
- (BOOL) isBlankString:(NSString *)string {
    
    if (string == nil || string == NULL) {
        
        return YES;
        
    }
    
    if ([string isKindOfClass:[NSNull class]]) {
        
        return YES;
        
    }
    
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        
        return YES;
        
    }
    
    return NO;
    
}

     @end

